package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OSSProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Slf4j
@Service
public class AliAuthServiceImpl implements AliAuthService {
    private OSSProperties prop;

    private OSS client;

    public AliAuthServiceImpl(OSSProperties prop, OSS client) {
        this.prop = prop;
        this.client = client;
    }

    @Override
    public AliOssSignatureDTO getSignature() {
        //计算过期时间
        try {
            long expireTime = prop.getExpireTime();
            long l = System.currentTimeMillis() + expireTime;
            Date date = new Date(l);
            //设置上传策略
            PolicyConditions policyConditions = new PolicyConditions();
            //文件大小限制
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,0,prop.getMaxFileSize());
            //上传目录
            policyConditions.addConditionItem(MatchMode.StartWith,PolicyConditions.COND_KEY,prop.getDir());
            //生产策略
            String s = client.generatePostPolicy(date, policyConditions);
            //编码
            byte[] bytes = s.getBytes("utf-8");
            String s1 = BinaryUtil.toBase64String(bytes);
            //生产签名
            String s2 = client.calculatePostSignature(s);
            //封装要返回的结果

            return  AliOssSignatureDTO.of(prop.getAccessKeyId(),prop.getHost(),s1,s2,l,prop.getDir());
        } catch (UnsupportedEncodingException e) {
            log.error("上传文件失败，原因：{}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败！", e);
        }
    }
}
